import React, { useReducer, useEffect, Fragment } from 'react';
import { Card, Icon, Modal, notification } from 'antd';
import LeavesForm from './components/LeavesForm';
import TableList from './components/TableList';
import { SIZE, PAGE } from '@/utils/constant';
import { teacherLeaves, editLeavesL } from '@/services/api';

interface initial {
  loading: boolean;
  data: [];
  pagination: object;
  searchValue: object;
}

const initialState: initial = {
  loading: false,
  data: [],
  pagination: {
    showSizeChanger: true,
  },
  searchValue: {},
};

const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1597145_clhh0n14pgn.js', // 在 iconfont.cn 上生成
});

const reducer = (state: any, { type, payload }: any) => {
  switch (type) {
    case 'OPEN_LOADING':
      return {
        ...state,
        loading: true,
      };
    case 'CLOSED_LOADING':
      return {
        ...state,
        loading: false,
      };
    case 'GET_DATA':
      return {
        ...state,
        data: payload,
      };
    case 'CHANGE_PAGINATION':
      return {
        ...state,
        pagination: payload,
      };
    case 'SEARCH_VALUE':
      return {
        ...state,
        searchValue: payload,
      };
    default:
      return state;
  }
};

const List = () => {
  const [{ loading, data, pagination, searchValue }, dispatch]: any = useReducer(
    reducer,
    initialState,
  );
  const pager = JSON.parse(JSON.stringify(pagination));
  useEffect(() => {
    dispatch({
      type: 'OPEN_LOADING',
    });
    teacherLeaves({ page: PAGE, size: SIZE })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  }, []);

  const onChange = (changePagination: any) => {
    pager.current = changePagination.current;
    pager.pageSize = changePagination.pageSize;
    dispatch({
      type: 'CHANGE_PAGINATION',
      payload: pager,
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    teacherLeaves({
      ...searchValue,
      page: changePagination.current,
      size: changePagination.pageSize,
    })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  };

  const columns = [
    {
      title: '姓名',
      key: 'teacher',
      dataIndex: 'teacher',
      render: (text: any) => <span>{text && text.name}</span>,
    },
    {
      title: '开始时间',
      key: 'started_at',
      dataIndex: 'started_at',
    },
    {
      title: '结束时间',
      key: 'ended_at',
      dataIndex: 'ended_at',
    },
    {
      title: '请假原因',
      key: 'reason',
      dataIndex: 'reason',
    },
    {
      title: '请假状态',
      key: 'status',
      dataIndex: 'status',
      render: (text: any) => {
        if (text === 0) {
          return (
            <span>
              <MyIcon type="icon-tubiaozhizuo-" />
              申请中
            </span>
          );
        }
        if (text === 1) {
          return (
            <span>
              <MyIcon type="icon-tubiaozhizuo--open" />
              已同意
            </span>
          );
        }
        if (text === 2) {
          return (
            <span>
              <MyIcon type="icon-tubiaozhizuo--closed" />
              已拒绝
            </span>
          );
        }
        return null;
      },
    },
    {
      title: '操作',
      width: 100,
      key: 'option',
      valueType: 'option',
      render: (text: any) => (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <a
            onClick={e => {
              e.preventDefault();
              const {
                id,
                leave_type_id,
                student_id,
                teacher_id,
                role_id,
                started_at,
                ended_at,
                reason,
                status,
              } = text;
              const newValue: any = {
                id,
                leave_type_id,
                student_id,
                teacher_id,
                role_id,
                started_at,
                ended_at,
                reason,
                status,
              };
              newValue.status = 1;
              Modal.confirm({
                content: '确认同意',
                onOk: () => {
                  editLeavesL(newValue).then((resp: any) => {
                    if (resp.status === 'success') {
                      notification.success({
                        message: '已同意请假',
                      });
                      dispatch({
                        type: 'OPEN_LOADING',
                      });
                      teacherLeaves({ ...searchValue, page: pager.current, size: pager.pageSize })
                        .then((res: any) => {
                          if (res.status === 'success') {
                            dispatch({
                              type: 'GET_DATA',
                              payload: res.data.data,
                            });
                            dispatch({
                              type: 'CHANGE_PAGINATION',
                              payload: {
                                ...pager,
                                total: res.data.meta.total,
                              },
                            });
                          }
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        })
                        .catch(() => {
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        });
                    }
                  });
                },
              });
            }}
          >
            同意
          </a>
          <a
            onClick={e => {
              e.preventDefault();
              const {
                id,
                leave_type_id,
                student_id,
                teacher_id,
                role_id,
                started_at,
                ended_at,
                reason,
                status,
              } = text;
              const newValue: any = {
                id,
                leave_type_id,
                student_id,
                teacher_id,
                role_id,
                started_at,
                ended_at,
                reason,
                status,
              };
              newValue.status = 2;
              Modal.confirm({
                content: '确认拒绝',
                onOk: () => {
                  editLeavesL(newValue).then((resp: any) => {
                    if (resp.status === 'success') {
                      notification.error({
                        message: '已拒绝请假',
                      });
                      dispatch({
                        type: 'OPEN_LOADING',
                      });
                      teacherLeaves({ ...searchValue, page: pager.current, size: pager.pageSize })
                        .then((res: any) => {
                          if (res.status === 'success') {
                            dispatch({
                              type: 'GET_DATA',
                              payload: res.data.data,
                            });
                            dispatch({
                              type: 'CHANGE_PAGINATION',
                              payload: {
                                ...pager,
                                total: res.data.meta.total,
                              },
                            });
                          }
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        })
                        .catch(() => {
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        });
                    }
                  });
                },
              });
            }}
          >
            拒绝
          </a>
        </div>
      ),
    },
  ];

  return (
    <Fragment>
      <Card title="教师请假">
        <LeavesForm dispatch={dispatch} />
      </Card>
      <Card className="pageCard">
        <TableList
          rowKey="id"
          dataSource={data}
          columns={columns}
          loading={loading}
          pagination={pagination}
          onChange={onChange}
        />
      </Card>
    </Fragment>
  );
};

export default List;
